const Title = require('../models/titleModel'); // 确保路径正确

// 获取所有标题
const getTitles = async (req, res) => {
  try {
    const { page = 1, limit = 15 } = req.query; // 获取请求中的page和limit参数，默认值为1和15
    const pageNumber = parseInt(page, 10);
    const limitNumber = parseInt(limit, 10);

    // 计算跳过的数量
    const skip = (pageNumber - 1) * limitNumber;

    // 查询数据库，应用排序和分页
    const titles = await Title.find().sort({ timestamp: -1 }).skip(skip).limit(limitNumber).lean();

    // 查询总数以便于计算总页数
    const totalTitles = await Title.countDocuments();

    const modifiedTitles = titles.map((item, index) => ({
      index: skip + index + 1, // 添加序号，从1开始
      ...item,
      isUsed: item.isUsed ? '是' : '否',
    }));

    const response = {
      code: 0,
      status: 'success',
      message: '获取标题成功',
      data: modifiedTitles,
      count: totalTitles, // 添加总数字段
      pagination: {
        currentPage: pageNumber,
        totalPages: Math.ceil(totalTitles / limitNumber),
        totalItems: totalTitles,
      },
    };

    res.json(response);
  } catch (error) {
    res.status(500).json({ message: '获取标题失败', error: error.message });
  }
};

// 添加新标题
const addTitle = async (req, res) => {
  const { titleName, titleType, isUsed } = req.body;

  if (!titleName) {
    return res.status(400).json({ message: '标题名称不能为空' });
  }

  try {
    const title = new Title({ titleName, titleType, isUsed });
    await title.save();
    res.status(201).json(title);
  } catch (error) {
    let errorMessage = error.message
    if (error.name === 'MongoError' && error.code === 11000) {
      errorMessage = '已存在相同标题名称'
    }
    res.status(500).json({ message: '添加标题失败', error: errorMessage });
  }
};

// 更新标题
const updateTitles = async (req, res) => {
  const { titleNames, isUsed } = req.body;

  if (!Array.isArray(titleNames) || titleNames.length === 0) {
    return res.status(400).json({ message: 'titleNames 必须是一个非空数组' });
  }

  try {
    const updates = await Promise.all(
      titleNames.map(async (titleName) => {
        const title = await Title.findOne({ titleName });
        if (!title) {
          return { titleName, message: '标题未找到' };
        }

        title.isUsed = isUsed !== undefined ? isUsed : title.isUsed;
        const updatedTitle = await title.save();
        return updatedTitle;
      })
    );

    res.json(updates);
  } catch (error) {
    res.status(500).json({ message: '更新标题失败', error: error.message });
  }
};

// 删除标题
const deleteTitles = async (req, res) => {
  const { titleNames } = req.body; // 获取请求体中的 titleNames 数组

  if (!Array.isArray(titleNames) || titleNames.length === 0) {
    return res.status(400).json({ message: '未选择标题' });
  }

  try {
    const result = await Title.deleteMany({ titleName: { $in: titleNames } });

    if (result.deletedCount === 0) {
      return res.status(404).json({ message: '没有找到匹配的标题' });
    }

    res.json({ message: `${result.deletedCount} 个标题已删除` });
  } catch (error) {
    res.status(500).json({ message: '删除标题失败', error: error.message });
  }
};



module.exports = { getTitles, addTitle, updateTitles, deleteTitles };

